<template>
  <div class="orders-page">
    <el-card class="page-container">
      <template #header>
        <div class="card-header">
          <span>订单管理</span>
          <el-button type="primary" @click="handleAdd">
            <el-icon><Plus /></el-icon>
            新增订单
          </el-button>
        </div>
      </template>
      
      <!-- 搜索表单 -->
      <el-form
        :model="searchForm"
        :inline="true"
        class="search-form"
      >
        <el-form-item label="订单号">
          <el-input
            v-model="searchForm.order_no"
            placeholder="请输入订单号"
            clearable
          />
        </el-form-item>
        
        <el-form-item label="学员姓名">
          <el-input
            v-model="searchForm.student_name"
            placeholder="请输入学员姓名"
            clearable
          />
        </el-form-item>
        
        <el-form-item label="状态">
          <el-select
            v-model="searchForm.status"
            placeholder="请选择状态"
            clearable
          >
            <el-option label="待支付" value="pending" />
            <el-option label="已支付" value="paid" />
            <el-option label="已退款" value="refunded" />
            <el-option label="已取消" value="cancelled" />
          </el-select>
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
      
      <!-- 数据表格 -->
      <el-table
        :data="tableData"
        v-loading="loading"
        class="table-container"
        stripe
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="order_no" label="订单号" width="140" />
        <el-table-column label="学员姓名" width="120">
          <template #default="{ row }">
            {{ getStudentName(row.student_id) }}
          </template>
        </el-table-column>
        <el-table-column label="课程名称" width="180">
          <template #default="{ row }">
            {{ getCourseName(row.course_id) }}
          </template>
        </el-table-column>
        <el-table-column prop="should_pay_amount" label="应缴金额" width="120">
          <template #default="{ row }">
            ¥{{ row.should_pay_amount }}
          </template>
        </el-table-column>
        <el-table-column prop="actual_pay_amount" label="实缴金额" width="120">
          <template #default="{ row }">
            ¥{{ row.actual_pay_amount }}
          </template>
        </el-table-column>
        <el-table-column prop="payment_method" label="支付方式" width="100" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag
              :type="getStatusType(row.status)"
              size="small"
            >
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="order_date" label="订单日期" width="160" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button
              type="primary"
              size="small"
              @click="handleEdit(row)"
            >
              编辑
            </el-button>
            <el-button
              type="success"
              size="small"
              @click="handlePayment(row)"
            >
              支付
            </el-button>
            <el-button
              type="danger"
              size="small"
              @click="handleDelete(row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页组件 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    
    <!-- 新增/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="700px"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="formRules"
        label-width="120px"
        class="form-container"
      >
        <el-form-item label="订单号" prop="order_no">
          <el-input v-model="form.order_no" placeholder="请输入订单号" />
        </el-form-item>
        
        <el-form-item label="学员" prop="student_id">
          <el-select v-model="form.student_id" placeholder="请选择学员">
            <el-option
              v-for="student in students"
              :key="student.id"
              :label="student.name"
              :value="student.id"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="课程" prop="course_id">
          <el-select v-model="form.course_id" placeholder="请选择课程">
            <el-option
              v-for="course in courses"
              :key="course.id"
              :label="course.name"
              :value="course.id"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="支付方式" prop="payment_method">
          <el-select v-model="form.payment_method" placeholder="请选择支付方式">
            <el-option label="支付宝" value="支付宝" />
            <el-option label="微信" value="微信" />
            <el-option label="银行卡" value="银行卡" />
            <el-option label="现金" value="现金" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="报名类型" prop="registration_type">
          <el-select v-model="form.registration_type" placeholder="请选择报名类型">
            <el-option label="新报名" value="新报名" />
            <el-option label="续费" value="续费" />
            <el-option label="转班" value="转班" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="应缴金额" prop="should_pay_amount">
          <el-input-number v-model="form.should_pay_amount" :min="0" :precision="2" />
        </el-form-item>
        
        <el-form-item label="实缴金额" prop="actual_pay_amount">
          <el-input-number v-model="form.actual_pay_amount" :min="0" :precision="2" />
        </el-form-item>
        
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio label="pending">待支付</el-radio>
            <el-radio label="paid">已支付</el-radio>
            <el-radio label="refunded">已退款</el-radio>
            <el-radio label="cancelled">已取消</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitting">
          确定
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { getOrders, createOrder, updateOrder, deleteOrder } from '@/api/order'
import { getStudents } from '@/api/student'
import { getCourses } from '@/api/course'
import type { Order, Student, Course } from '@/api/order'

// 响应式数据
const loading = ref(false)
const submitting = ref(false)
const dialogVisible = ref(false)
const dialogTitle = ref('')
const formRef = ref<FormInstance>()

// 搜索表单
const searchForm = reactive({
  order_no: '',
  student_name: '',
  status: ''
})

// 表格数据
const tableData = ref<Order[]>([])
const students = ref<Student[]>([])
const courses = ref<Course[]>([])

// 分页数据
const pagination = reactive({
  current: 1,
  pageSize: 20,
  total: 0
})

// 表单数据
const form = reactive({
  id: null,
  order_no: '',
  student_id: '',
  course_id: '',
  payment_method: '',
  registration_type: '新报名',
  should_pay_amount: 0,
  actual_pay_amount: 0,
  status: 'pending'
})

// 表单验证规则
const formRules: FormRules = {
  order_no: [
    { required: true, message: '请输入订单号', trigger: 'blur' }
  ],
  student_id: [
    { required: true, message: '请选择学员', trigger: 'change' }
  ],
  course_id: [
    { required: true, message: '请选择课程', trigger: 'change' }
  ],
  should_pay_amount: [
    { required: true, message: '请输入应缴金额', trigger: 'blur' }
  ]
}

// 方法
const getStatusType = (status: string) => {
  const statusMap: Record<string, string> = {
    pending: 'warning',
    paid: 'success',
    refunded: 'info',
    cancelled: 'danger'
  }
  return statusMap[status] || 'info'
}

const getStatusText = (status: string) => {
  const statusMap: Record<string, string> = {
    pending: '待支付',
    paid: '已支付',
    refunded: '已退款',
    cancelled: '已取消'
  }
  return statusMap[status] || status
}

const getStudentName = (studentId: number) => {
  if (!students.value || !Array.isArray(students.value)) {
    return '加载中...'
  }
  const student = students.value.find(s => s.id === studentId)
  return student ? student.name : '未知学员'
}

const getCourseName = (courseId: number) => {
  if (!courses.value || !Array.isArray(courses.value)) {
    return '加载中...'
  }
  const course = courses.value.find(c => c.id === courseId)
  return course ? course.name : '未知课程'
}

const handleSearch = () => {
  pagination.current = 1
  loadData()
}

const handleReset = () => {
  searchForm.order_no = ''
  searchForm.student_name = ''
  searchForm.status = ''
  handleSearch()
}

const handleSizeChange = (size: number) => {
  pagination.pageSize = size
  pagination.current = 1
  loadData()
}

const handleCurrentChange = (page: number) => {
  pagination.current = page
  loadData()
}

const handleAdd = () => {
  dialogTitle.value = '新增订单'
  form.id = null
  form.order_no = ''
  form.student_id = ''
  form.course_id = ''
  form.payment_method = ''
  form.registration_type = '新报名'
  form.should_pay_amount = 0
  form.actual_pay_amount = 0
  form.status = 'pending'
  dialogVisible.value = true
}

const handleEdit = (row: any) => {
  dialogTitle.value = '编辑订单'
  // 只复制需要的字段，避免数字键问题
  Object.assign(form, {
    id: row.id,
    order_no: row.order_no,
    student_id: row.student_id,
    course_id: row.course_id,
    should_pay_amount: row.should_pay_amount,
    actual_pay_amount: row.actual_pay_amount,
    status: row.status
  })
  dialogVisible.value = true
}

const handlePayment = (row: any) => {
  ElMessage.info('支付功能开发中')
}

const handleDelete = async (row: any) => {
  try {
    await ElMessageBox.confirm('确定要删除这个订单吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    await deleteOrder(row.id)
    ElMessage.success('删除成功')
    loadData()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

const handleSubmit = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (valid) {
      submitting.value = true
      try {
        if (form.id) {
          await updateOrder(form.id, form)
          ElMessage.success('更新成功')
        } else {
          await createOrder(form)
          ElMessage.success('新增成功')
        }
        
        dialogVisible.value = false
        loadData()
      } catch (error) {
        ElMessage.error('操作失败')
      } finally {
        submitting.value = false
      }
    }
  })
}

const loadData = async () => {
  try {
    loading.value = true
    
    console.log('开始加载数据...')
    
    // 并行获取订单、学员和课程数据
    const [ordersResponse, studentsResponse, coursesResponse] = await Promise.all([
      getOrders({
        page: pagination.current,
        size: pagination.pageSize,
        order_no: searchForm.order_no,
        status: searchForm.status
      }),
      getStudents({ page: 1, size: 1000 }),
      getCourses({ page: 1, size: 100 })
    ])
    
    console.log('订单数据:', ordersResponse)
    console.log('学员数据:', studentsResponse)
    console.log('课程数据:', coursesResponse)
    
    tableData.value = ordersResponse.items || []
    pagination.total = ordersResponse.total || 0
    students.value = studentsResponse.items || []
    courses.value = coursesResponse.items || []
    
    console.log('数据加载完成')
    
  } catch (error) {
    console.error('获取数据失败:', error)
    ElMessage.error(`获取数据失败: ${error.message || error}`)
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  loadData()
})
</script>

<style lang="scss" scoped>
.orders-page {
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-weight: bold;
  }
  
  .search-form {
    margin-bottom: 20px;
    padding: 20px;
    background: #f8f9fa;
    border-radius: 4px;
  }
  
  .pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: center;
  }
}
</style>
